package org.yogthos;

import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

public class Penguin extends AnimatedSprite {
	private final long UPDATE_INTERVAL = 1000;
	private PhysicsHandler physicsHandler;
	private int cameraWidth;
	private int cameraHeight;
	private long lastUpdateTime;
	

	public Penguin(int cameraWidth, int cameraHeight, float pX, float pY, float xv, float yv, TiledTextureRegion pTextureRegion) {
		super(pX, pY, pTextureRegion);
		this.physicsHandler = new PhysicsHandler(this);
		this.registerUpdateHandler(this.physicsHandler);
		this.physicsHandler.setVelocity(xv, yv);
		this.cameraHeight = cameraHeight;
		this.cameraWidth = cameraWidth;
		lastUpdateTime = System.currentTimeMillis();
	}

	@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {
		float xv = this.physicsHandler.getVelocityX();
		float yv = this.physicsHandler.getVelocityY();

		if (this.mX + this.getWidth() > cameraWidth && xv > 0 || this.mX < this.getWidth() && xv < 0)
			this.physicsHandler.setVelocityX(-xv);

		if (this.mY + this.getHeight() > cameraHeight && yv > 0 || this.mY < this.getHeight() && yv < 0)
			this.physicsHandler.setVelocityY(-yv);

		long currentTime = System.currentTimeMillis();
		if (getCurrentTileIndex() == 1 && currentTime - lastUpdateTime > UPDATE_INTERVAL) {
			setCurrentTileIndex(0);
			lastUpdateTime = currentTime;
		}
		super.onManagedUpdate(pSecondsElapsed);
	}
	
	public void setVelosity(Float xt, Float yt)
	{
		float xv = this.physicsHandler.getVelocityX();
		float yv = this.physicsHandler.getVelocityY();
		// Calculation of the angle
		double alpha= Math.atan2(yt-this.mY, xt-this.mX);
		this.physicsHandler.setVelocityX((float) (xv*Math.cos(alpha)-yv*Math.sin(alpha)));
		this.physicsHandler.setVelocityY((float) (xv*Math.sin(alpha)+yv*Math.cos(alpha)));
	}
}
